#!/bin/bash

echo "=== RocketMQ 网络检查和诊断脚本 ==="
echo ""

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "错误: Docker未运行，请先启动Docker服务"
    exit 1
fi

echo "✓ Docker服务正在运行"
echo ""

# 检查网络列表
echo "=== 当前Docker网络列表 ==="
docker network ls
echo ""

# 检查RocketMQ网络
echo "=== 检查RocketMQ网络 ==="
if docker network ls | grep -q "rocketmq"; then
    echo "✓ rocketmq网络存在"
    echo ""
    echo "网络详细信息："
    docker network inspect rocketmq --format='{{.Name}}: {{.Driver}} - {{.IPAM.Config}}'
    echo ""
    
    # 检查网络中的容器
    echo "网络中的容器："
    docker network inspect rocketmq --format='{{range .Containers}}{{.Name}} ({{.IPv4Address}}){{"\n"}}{{end}}'
    echo ""
else
    echo "⚠ rocketmq网络不存在"
    echo ""
fi

# 检查RocketMQ容器状态
echo "=== 检查RocketMQ容器状态 ==="
if docker ps -a | grep -q "rmqnamesrv"; then
    echo "✓ NameServer容器存在"
    docker ps -a | grep "rmqnamesrv"
else
    echo "⚠ NameServer容器不存在"
fi

if docker ps -a | grep -q "rmqbroker"; then
    echo "✓ Broker容器存在"
    docker ps -a | grep "rmqbroker"
else
    echo "⚠ Broker容器不存在"
fi

echo ""

# 检查docker-compose状态
echo "=== 检查Docker Compose状态 ==="
if [ -f "docker-compose.yml" ]; then
    echo "✓ docker-compose.yml文件存在"
    
    # 检查服务状态
    if command -v docker-compose &> /dev/null; then
        echo "检查服务状态："
        docker-compose ps
        echo ""
    else
        echo "⚠ docker-compose命令不可用"
    fi
else
    echo "⚠ docker-compose.yml文件不存在"
fi

echo ""

# 提供解决方案
echo "=== 解决方案 ==="
if ! docker network ls | grep -q "rocketmq"; then
    echo "1. 启动RocketMQ服务："
    echo "   docker-compose up -d"
    echo ""
    echo "2. 或者手动创建网络："
    echo "   docker network create rocketmq"
    echo ""
    echo "3. 检查网络是否创建成功："
    echo "   docker network ls"
    echo ""
else
    echo "✓ 网络已存在，可以继续运行应用部署脚本"
fi

echo "=== 常用命令 ==="
echo "启动RocketMQ: docker-compose up -d"
echo "停止RocketMQ: docker-compose down"
echo "查看日志: docker-compose logs -f"
echo "重启服务: docker-compose restart"
echo "查看网络: docker network inspect rocketmq"

